package com.hxs.hxsserver.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {

    // AES 加密
    public static String encrypt(String plainText, String key) throws Exception {
        // 初始化加密器
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        // 加密
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // AES 解密
    public static String decrypt(String cipherText, String key) throws Exception {
        // 初始化解密器
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        // 解密
        byte[] decodedBytes = Base64.getDecoder().decode(cipherText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }

    // 随机生成 AES 密钥
    public static String generateAESKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128); // 默认 128 位密钥
        SecretKey secretKey = keyGen.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    public static void main(String[] args) {
        try {
            String key = "123456789012345a"; // 16 位密钥
            String plainText = "Hello, AES!";

            // 加密
            String cipherText = encrypt(plainText, key);
            System.out.println("加密后的密文: " + cipherText);

            // 解密
            String decryptedText = decrypt(cipherText, key);
            System.out.println("解密后的明文: " + decryptedText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
